import React, { useState } from "react";
import axios from "axios";
import Cookies from "js-cookie";
import "../componentsCss/login.css";

function Login({ closeLogin }) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [errorMessage, setErrorMessage] = useState("");

  const handleLogin = async () => {
    if (!username || !password) {
      setErrorMessage("用户名和密码不能为空");
      return;
    }

    try {
      const response = await axios.post(
        "http://localhost:8080/user/login",
        null,
        {
          params: {
            username: username,
            password: password,
          },
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        }
      );
      console.log("登录成功:", response.data.message);
      // 将 token 存储在 cookie 中
      Cookies.set("token", response.data.data.token, { expires: 7 });
      // 关闭登录窗口
      closeLogin();
    } catch (error) {
      console.error("登录失败:", error);
      setErrorMessage("登录失败，请检查用户名和密码");
    }
  };

  const handleRegister = async () => {
    if (!username || !password) {
      setErrorMessage("用户名和密码不能为空");
      return;
    }

    try {
      const registerResponse = await axios.post(
        "http://localhost:8080/user/register",
        null,
        {
          params: {
            username: username,
            password: password,
          },
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        }
      );
      console.log("注册成功:", registerResponse.data.message);

      // 自动登录
      const loginResponse = await axios.post(
        "http://localhost:8080/user/login",
        null,
        {
          params: {
            username: username,
            password: password,
          },
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        }
      );
      console.log("自动登录成功:", loginResponse.data.message);
      // 将 token 存储在 cookie 中
      Cookies.set("token", loginResponse.data.data.token, { expires: 7 });
      // 关闭登录窗口
      closeLogin();
    } catch (error) {
      console.error("注册或自动登录失败:", error);
      setErrorMessage("注册或自动登录失败，请重试");
    }
  };

  return (
    <div className="login-modal">
      <div className="login-content">
        <span className="close-button" onClick={closeLogin}>
          &times;
        </span>
        <h2>登录</h2>
        {errorMessage && <p className="error-message">{errorMessage}</p>}
        <input
          type="text"
          placeholder="账号"
          className="login-input"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
        />
        <input
          type="password"
          placeholder="密码"
          className="login-input"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <div className="button-group">
          <button className="submit-button" onClick={handleLogin}>
            登录
          </button>
          <button className="register-button" onClick={handleRegister}>
            注册
          </button>
        </div>
      </div>
    </div>
  );
}

export default Login;
